package cn.zhqr.core.service;

import cn.zhqr.db.model.Coupon;
import cn.zhqr.db.model.UserCoupon;
import cn.zhqr.db.model.UserOrder;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

public class UserCouponService {
    public static final UserCouponService instance = new UserCouponService();
    public static final Logger logger = Logger.getLogger(UserCouponService.class);

    public BigDecimal useCoupon(UserOrder washOrder, BigInteger orderNo, BigDecimal orderAmount, BigDecimal payAmount) {
        List<UserCoupon> couponList = UserCoupon.dao.findValidByUserId(washOrder.getUserId());
        for(UserCoupon userCoupon : couponList){
            if(userCoupon.getType() == Coupon.TYPE_FULL_FREE && orderAmount.compareTo(userCoupon.getDiscountAmount()) <= 0){
                //符合免单条件，本单全免
                payAmount = BigDecimal.ZERO;
                userCoupon.setStatus(UserCoupon.STATUS_USED);
                userCoupon.setOrderNo(orderNo);
                userCoupon.update();
            }else if(userCoupon.getType() == Coupon.TYPE_DISCOUNT_AMOUNT && orderAmount.compareTo(userCoupon.getMinOrderAmount()) >= 0){
                //符合满减券使用条件，减免金额
                payAmount = orderAmount.subtract(userCoupon.getDiscountAmount());
                userCoupon.setStatus(UserCoupon.STATUS_USED);
                userCoupon.setOrderNo(orderNo);
                userCoupon.update();
            }else if(userCoupon.getType()==Coupon.TYPE_DISCOUNT_RATE && orderAmount.compareTo(userCoupon.getMinOrderAmount()) >= 0){
                //符合折扣券使用条件，打折
                payAmount = orderAmount.multiply(userCoupon.getDiscountRate());
                userCoupon.setStatus(UserCoupon.STATUS_USED);
                userCoupon.setOrderNo(orderNo);
                userCoupon.update();
            }
        }
        return payAmount;
    }
}
